<?php
/**
 * (Static)Library class for collaborative functionality in refworks module
 *
 * @copyright &copy; 2009 The Open University
 * @author j.platts@open.ac.uk
 * @author Author_Name_2@open.ac.uk
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 * @package refworks/collab
 */

class refworks_collab_lib {
    public static $accsavail = array();//Array of accounts users has access to: gets populated by get_user_accounts()
    //accounts in these arrays take the format of object ->id, ->name
    public static $accsown = array();//Array of accounts user has 'owner' permission over: gets populated by get_user_owned_accounts()
    public static $dormaccs = array();//Array of all dormant accounts
    /**
     * Returns array of accounts user has been given permission to access
     * Also sets this value to $accsavail - so can be re-accessed without db call
     * @param $userid - moodle userid of user
     * @return array
     */
    public static function get_user_accounts($userid, $update=false){
        if(!$update && isset(self::$accsavail[0])){
            //already done, no need to re-access db unless forced $update
            return self::$accsavail;
        }
        global $CFG;
        $acctable = $CFG->prefix.'refworks_collab_accs';
        $usertable = $CFG->prefix.'refworks_collab_users';
        if(!$accs = get_records_sql("SELECT $acctable.id,name FROM $acctable INNER JOIN $usertable ON $usertable.userid = $userid AND $acctable.id = $usertable.accid WHERE $acctable.datedeleted IS NULL ORDER BY name")){
            return array();
        }
        
        self::$accsavail = $accs;
        return $accs;
    }

    /**
     * Returns array of accounts that user has 'owner' status
     * Also sets this value to $accsown - so can be re-accessed without db call
     * @param $userid
     * @return array
     */
    public static function get_user_owned_accounts($userid){
        
        global $CFG;
        $acctable = $CFG->prefix.'refworks_collab_accs';
        $usertable = $CFG->prefix.'refworks_collab_users';
        if(!$accs = get_records_sql("SELECT $acctable.id,name,created,lastlogin FROM $acctable INNER JOIN $usertable ON $usertable.userid = $userid AND $usertable.owner=1 AND $acctable.id = $usertable.accid WHERE $acctable.datedeleted IS NULL ORDER BY name")){
            return array();
        }
        
        self::$accsown = $accs;
        return $accs;
    }

    /**
     * Returns array of all account records in the database
     * @return array
     */
    public static function get_all_accounts(){
        global $CFG;
        $acctable = $CFG->prefix.'refworks_collab_accs';
        //if(!$result=get_records('refworks_collab_accs','','','name','id,name,created,lastlogin')){
        if(!$result = get_records_sql("SELECT id, name, created, lastlogin FROM $acctable WHERE datedeleted IS NULL")){
            return array();
        }else{
            return $result;
        }
    }
    
    /**
     * Returns array of all dormant account records in the database
     * @return array
     */
    public static function get_all_dormant_accounts($update=false){
        if(!$update && isset(self::$dormaccs[0])){
        //already done, no need to re-access db unless forced $update
        return self::$dormaccs;
        }
        global $CFG;
        $acctable = $CFG->prefix.'refworks_collab_accs';
        if(!$dormaccs = get_records_sql("SELECT $acctable.id,name,login,created,lastlogin,datedeleted FROM $acctable WHERE datedeleted IS NOT NULL ORDER BY name")){
            return array();
        }
        self::$dormaccs = $dormaccs;
        return $dormaccs;
    }

    /**
     * Checks if user can access a particular account id
     * @param $accid int: accounts id in db table refworks_collab_accs
     * @return bool
     */
    public static function can_user_access_account($accid){
        foreach(self::$accsavail as $acc){
            if($acc->id == $accid){
                return true;
            }
        }
        return false;
    }

    /**
     * Checks if user can administer a particular account id
     * @param $accid int: accounts id in db table refworks_collab_accs
     * @return bool
     */
    public static function can_user_own_account($accid){
        foreach(self::$accsown as $acc){
            if($acc->id == $accid){
                return true;
            }
        }
        return false;
    }

    /**
     * Updates the db field lastlogin for account to record time of last login
     * @param $accid int: account id
     * @return
     */
    public function update_login_time($accid){
        set_field('refworks_collab_accs','lastlogin',time(),'id',$accid);
    }

    /**
     * Returns array of user rows (from user id) that are in account
     * @param $accid int: accounts id in db table refworks_collab_accs
     * @param $who int: 0-all, 1-owners, 2-non-owners
     * @param $excludeself bool: default excludes current user from list
     * @return array
     */
    public static function get_participants($accid, $who=0, $excludeself=true){
        global $USER, $CFG;
        $ownercheck = -1;
        if($who==1){
            $ownercheck = 1;
        }else if($who==2){
            $ownercheck = 0;
        }
        
        global $CFG;
        $usertable = $CFG->prefix.'user';
        $accusertable = $CFG->prefix.'refworks_collab_users';
        
        //whether results inc cur user...
        if($excludeself){
            $exclude = "AND $usertable.id <> $USER->id";
        }else{
            $exclude = "";
        }
        
        if($ownercheck == -1){
            //get all users on this acc
            if(!$result=get_records_sql("SELECT $usertable.id,firstname,lastname,username FROM $usertable INNER JOIN $accusertable ON $accusertable.accid = $accid AND $accusertable.userid = $usertable.id $exclude ORDER BY firstname")){
                return array();
            }
        }else{
            //only get users who are/n't owners
            if(!$result=get_records_sql("SELECT $usertable.id,firstname,lastname,username FROM $usertable INNER JOIN $accusertable ON $accusertable.accid = $accid AND $accusertable.owner = $ownercheck AND $accusertable.userid = $usertable.id $exclude ORDER BY firstname")){
                return array();
            }
        }
        
        return $result;
    }

    /**
     * Adds a new user to the account
     * @param $accid int: accounts id in db table refworks_collab_accs
     * @param $userid
     * @param $asowner
     * @return
     */
    public static function add_participant($accid, $userid, $asowner=0){
        $newrec = new stdClass();
        $newrec->userid=$userid;
        $newrec->accid=$accid;
        $newrec->owner=$asowner;

        if(record_exists('refworks_collab_users','userid',$userid,'accid',$accid)){
            $existrec=get_record('refworks_collab_users','userid',$userid,'accid',$accid);
            $existrec->owner=$asowner;
            update_record('refworks_collab_users',$existrec);
        }else{
            insert_record('refworks_collab_users',$newrec);
        }
    }

    public static function remove_participant($accid, $userid){
        delete_records('refworks_collab_users','userid',$userid,'accid',$accid);
    }

    /**
     * Permanently delete a shared account
     * @param $accid
     * @return true or false
     */
    public static function delete_account($accid){
        $userdelete = delete_records('refworks_collab_users','accid',$accid);
        $collabsdelete = delete_records('refworks_collab_accs','id',$accid);
        if($userdelete==false||$collabsdelete==false){
            return false;   
        }
        return true;
    }

    /**
     * Returns the record for the account
     * @param $accid
     * @return record object
     */
    
    public static function get_account_details($accid){
        return get_record('refworks_collab_accs','id',$accid);
    }
    /**
     * Rename an account
     * @param $id int: account id
     * @param $newname string: proposed acount name
     * @param $loginonly bool: true if you want to keep display name to original
     * @return success
     */
    public static function rename_account_details($id,$newname,$loginonly=false){
        $login = strtolower(str_replace(' ','_',$newname));
        //check if an account already exists with the proposed new login
        if(get_record('refworks_collab_accs','login',$login)){
            refworks_base::write_error(get_string('team_createacc_exists','refworks'));
        }else{
            $rec = new stdClass();
            $rec->id=$id;
            if(!$loginonly){
                $rec->name=$newname;
            }
            $rec->login=addslashes(htmlspecialchars($login,ENT_COMPAT,'utf-8',false));
            update_record('refworks_collab_accs',$rec);
            return true;
        }
        return false;
    }
    
    /**
     * Make an account dormant
     * @param $id int: account id
     * @return success
     */
    public static function make_account_dormant($id){
        $rec = new stdClass();
        $rec->id=$id;
        $rec->datedeleted=time();
        update_record('refworks_collab_accs',$rec);
        return true;
    }
    
    /**
     * Reactivate a dormant account
     * @param $id int: account id
     * @return success
     */
    public static function reactivate_dormant_account($id){
        $rec = new stdClass();
        $rec->id=$id;
        $rec->datedeleted=NULL;
        update_record('refworks_collab_accs',$rec);
        return true;
    }
}
?>